<?php
// +----------------------------------------------------------------------
// | WWW.0771MC.COM 广西南宁市铭成龙毅网络科技有限公司 出品
// +----------------------------------------------------------------------
// | Copyright (c) 2014 http://WWW.0771MC.COM All rights reserved.
// +----------------------------------------------------------------------
// | Author: 铭成龙毅 <service@0771mc.com> <http://www.0771MC.com>
// +----------------------------------------------------------------------
namespace Home\Controller;

use Think\Controller;
use Com\Wechat;

class WechatController extends Controller{
    /**
     * 微信消息接口入口
     * 所有发送到微信的消息都会推送到该操作
     * 所以，微信公众平台后台填写的api地址则为该操作的访问地址
     */
    public function index($id = ''){
        header("Content-Type:text/html; charset=utf-8");//不然返回中文乱码
        $token =C('cfg_wechat_token'); //微信后台填写的TOKEN


        /* 加载微信SDK */
        $wechat = new Wechat($token);

        /* 获取请求信息 */
        $data = $wechat->request();

        if($data && is_array($data)){

            /**
             * 你可以在这里分析数据，决定要返回给用户什么样的信息
             * 接受到的信息类型有9种，分别使用下面九个常量标识
             * Wechat::MSG_TYPE_TEXT       //文本消息
             * Wechat::MSG_TYPE_IMAGE      //图片消息
             * Wechat::MSG_TYPE_VOICE      //音频消息
             * Wechat::MSG_TYPE_VIDEO      //视频消息
             * Wechat::MSG_TYPE_MUSIC      //音乐消息
             * Wechat::MSG_TYPE_NEWS       //图文消息（推送过来的应该不存在这种类型，但是可以给用户回复该类型消息）
             * Wechat::MSG_TYPE_LOCATION   //位置消息
             * Wechat::MSG_TYPE_LINK       //连接消息
             * Wechat::MSG_TYPE_EVENT      //事件消息
             *
             * 事件消息又分为下面五种
             * Wechat::MSG_EVENT_SUBSCRIBE          //订阅
             * Wechat::MSG_EVENT_SCAN               //二维码扫描
             * Wechat::MSG_EVENT_LOCATION           //报告位置
             * Wechat::MSG_EVENT_CLICK              //菜单点击
             * Wechat::MSG_EVENT_MASSSENDJOBFINISH  //群发消息成功
             */

            $type=$data['MsgType'];//信息类型
            $event=$data['Event'];//事件类型

            switch ($type) {
                case Wechat::MSG_TYPE_TEXT://文本消息
                    $rcontent=$data['Content'];

                    $gongsi=mb_substr($rcontent, 0, 3, 'utf-8');//查询公司用
                    $mingcheng=mb_substr($rcontent, 3,mb_strlen($rcontent),'utf-8');
                    $mingcheng="entname:".urlencode($mingcheng);

                    if ($gongsi=="查公司") {
                        $type=Wechat::MSG_TYPE_TEXT;
                        $url="http://116.252.222.40:8888/search/?db=entmaininfo&keyword=".$mingcheng."&fields=id,entname,lerep,regno,dom&pagesize=undefined&page=undefined&variable=v1&_=1409572486934";       
                        $rdata=$this->getCurl($url);
                         if(empty($rdata['regno'])){
                            $content="没有找到相关公司信息！";
                         }else{
                            $content="公司：".mb_convert_encoding($rdata['entname'], "utf-8", "gb2312")."\n法人：".mb_convert_encoding($rdata['lerep'], "utf-8", "gb2312")."\n企业注册号：".$rdata['regno']."\n住址/营业地址:".mb_convert_encoding($rdata['dom'], "utf-8", "gb2312");
                        }
                        

                    }else{
                        $map['keywords']=array('like','%'.$rcontent.'%');
                        $dbdata=M('chatwords')->where($map)->limit(1)->order('sort DESC')->find();
                        if ($dbdata['isnews']) {
                            $type=Wechat::MSG_TYPE_NEWS;
                            $contents=array($dbdata['title'],$dbdata['content'],$dbdata['url'],C('cfg_weburl').$dbdata['picurl']);
                            $content=array($contents);
                        }else{
                            $type=Wechat::MSG_TYPE_TEXT;
                            $content=$dbdata['content'];
                        }
                    }
                    $wechat->response($content, $type);
                    //$wechat->replyText($data);
                    break;
                case Wechat::MSG_TYPE_EVENT://事件消息
                        switch ($event) {
                            case Wechat::MSG_EVENT_SUBSCRIBE://订阅
                                
                                $weburl=C('cfg_weburl');
                                $db=M('chatwords');
                                $wetype=C('cfg_wechat_type');

                                if ($wetype) {
                                    $type=Wechat::MSG_TYPE_NEWS;
                                    $where = array('isnews' => 1,'iszidong'=>1);
                                    $dbdata=$db->where($where)->limit(8)->order('sort DESC')->field('title,content,url,picurl')->select();

                                    $content=changeData($dbdata);

                                }else{
                                    $type=Wechat::MSG_TYPE_TEXT;
                                    $where=array('isnews'=>0,'iszidong'=>1);
                                    $content=$db->where($where)->limit(1)->order('sort DESC')->getField('content');

                                }
                                $wechat->response($content, $type);
                                break;
                            case Wechat::MSG_EVENT_CLICK://菜单点击
                                $key=$data['EventKey'];//微信上点击的KEY值
                                $db=M('chatwords');
                                $rs=M('chatmenu')->where(array('key'=>$key))->field('url,type')->find();
                                if ($rs['type']==1) {//如果是绑定关键字类型
                                     $map['keywords']=array('eq',$rs['url']);
                                     $dbdata=$db->where($map)->limit(1)->order('sort DESC')->find();

                                    if ($dbdata['isnews']) {
                                    $type=Wechat::MSG_TYPE_NEWS;
                                    $contents=array($dbdata['title'],$dbdata['content'],$dbdata['url'],C('cfg_weburl').$dbdata['picurl']);
                                        $content=array($contents);
                                    }else{
                                        $type=Wechat::MSG_TYPE_TEXT;
                                        $content=$dbdata['content'];
                                    }
                                    if (empty($content)) {
                                        $content="没有找到相关信息！";
                                    }
                                }
                                if ($rs['type']==2) {//绑定栏目ID 获取最新的8条数据组拼
                                    $type=Wechat::MSG_TYPE_NEWS;
                                    $table_name=M()->query("select tablename from __PREFIX__model where id=(select modelid from __PREFIX__category where id=".$rs['url'].")");
                                    $table_name=$table_name[0]['tablename'];
                                    $dbdata=M($table_name)->limit(8)->order('publishtime DESC')->field('title,description AS content,id AS url,litpic AS picurl,cid')->select();
                                    $dd=array();
                                    foreach ($dbdata as $key => $v) {
                                        $v['url']=C('cfg_weburl').'/Mobile/Show/index/cid/'.$v['cid'].'/id/'.$v['url'];
                                        unset($v['cid']);
                                        $dd[]=$v;
                                    }
                                    $content=changeData($dd);
                                }


                                $wechat->response($content, $type);
                                break;
                            
                            default:
                                # code...
                                break;
                        }
                    break;
                
                default:
                    # code...
                    break;
            }

            /*$content = ''; //回复内容，回复不同类型消息，内容的格式有所不同
            $type    = ''; //回复消息的类型*/

            /* 响应当前请求(自动回复) */
            //$wechat->response($content, $type);

            /**
             * 响应当前请求还有以下方法可以只使用
             * 具体参数格式说明请参考文档
             * 
             * $wechat->replyText($text); //回复文本消息
             * $wechat->replyImage($media_id); //回复图片消息
             * $wechat->replyVoice($media_id); //回复音频消息
             * $wechat->replyVideo($media_id, $title, $discription); //回复视频消息
             * $wechat->replyMusic($title, $discription, $musicurl, $hqmusicurl, $thumb_media_id); //回复音乐消息
             * $wechat->replyNews($news, $news1, $news2, $news3); //回复多条图文消息
             * $wechat->replyNewsOnce($title, $discription, $url, $picurl); //回复单条图文消息
             * 
             */
        }
    }

    public function getCurl($url){

        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, 1);        
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true) ; // 获取数据返回  
        curl_setopt($ch, CURLOPT_BINARYTRANSFER, true) ; // 在启用 CURLOPT_RETURNTRANSFER 时候将获取数据返回
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION,1);
        $output = curl_exec($ch);    
        $output=$this->filterData($output);
        $output= str_replace('{','',$output);
        $output= str_replace('}','',$output);
        $output= str_replace('"','',$output);
        $data=array();       
        $datas=explode(',', $output);
        foreach ($datas as $key => $value) {
            list($k,$v)=explode(':', $value);           
            $data[$k]=$v;
            
        }
        curl_close($ch);
        return $data;
    }

    public function filterData($tag){
        $result=array();
        preg_match_all("/(?:\[)(.*)(?:\])/i",$tag, $result); 
        return $result[1][0]; 
    }



    public function testData(){
        header("Content-Type:text/html; charset=utf-8");//不然返回中文乱码

        //$gongsi=mb_substr("查公司广西南宁市", 0, 3, 'utf-8');//查询公司用
        $gongsi=mb_substr("查公司广西南宁市", 3, mb_strlen("查公司广西南宁市"),'utf-8');//查询公司用
        print_r($gongsi);
        $db=M('chatwords');
        $where = array('isnews' => 1);
        $data=$db->where($where)->limit(8)->order('publictime DESC')-> field('title as "0",content as "1",url as "2",picurl as "3"')->select();
        print_r('<pre>');
        print_r($data);
        print_r('</pre>');

        $newdata=array();
        foreach ($data as $key => $value) {
            foreach ($value as $k => $v) {
                if ($k==3) {
                    $v=C('cfg_weburl').$v;
                }

                 $data[$key][$k]=$v;
            }
           
           // $data[$key]=$value;
        }
        print_r('===============================');
        print_r('<pre>');
        print_r($data);
        print_r('</pre>');
        print_r('===============================<br>');

        $changedata=changeData($data);
        print_r('-------------------------------------------------');
        print_r('<pre>');
        print_r($changedata);
        print_r('</pre>');
        print_r('-------------------------------------------------');
        $contents=array();
        //$b=array();
        foreach ($data as $key => $value) {
            //$contents.="array("."\"".$value['title']."\","."\"".$value['content']."\","."\"".$value['url']."\","."\"".$value['picurl']."\"),";

            foreach ($value as $k => $v) {
                
                if ($k=='content') {
                    $k=1;
                }
                if ($k=='url') {
                    $k=2;
                }
                if ($k=='picurl') {
                    $k=3;
                }
                if ($k=='title') {
                    $k=0;
                }
                $contents[$key][$k]=$v;
            }
             
            //$contents[$key]=$value;
        }
        //$content="array(".$contents.")";
        print_r('<pre>');
        //print_r($contents);
        print_r('</pre>');

        $contentd=array(
                                array("关注订阅立刻回复图文信息1","关注订阅立刻回复图文信息", "http://www.thinkphp.cn", "http://www.thinkphp.cn/Uploads/da/2014-08-25/53faf9f0a5c0a.jpg"),
                                array("关注订阅立刻回复图文信息2","关注订阅立刻回复图文信息", "http://www.thinkphp.cn", "http://www.thinkphp.cn/Uploads/da/2014-08-25/53faf9f0a5c0a.jpg"),
                                array("关注订阅立刻回复图文信息3","关注订阅立刻回复图文信息", "http://www.thinkphp.cn", "http://www.thinkphp.cn/Uploads/da/2014-08-25/53faf9f0a5c0a.jpg"),
                                );
        print_r('<pre>');
        print_r($contentd);
        print_r('</pre>');
    }

    public function testDatad(){
        header("Content-Type:text/html; charset=utf-8");//不然返回中文乱码
        $map['title']=array('like','%斯蒂%');
        $dbdata=M('chatwords')->where($map)->limit(1)->order('publictime DESC')->find();
        print_r('<pre>');
        print_r($dbdata['isnews']);
        print_r('</pre>');

        $conent="array("."'".$dbdata['title']."',"."'".$dbdata['content']."',"."'".$dbdata['url']."',"."'".C('cfg_weburl').$dbdata['picurl'] ."')";

        print_r($conent);

    }

    public function ddds(){
                header("Content-Type:text/html; charset=utf-8");
        $key='sp20150404944894';
        $rs=M('chatmenu')->where(array('key'=>$key))->field('url,type')->find();
        $table_name=M()->query("select tablename from __PREFIX__model where id=(select modelid from __PREFIX__category where id=".$rs['url'].")");
                                    $table_name=$table_name[0]['tablename'];
                                    $dbdata=M($table_name)->limit(8)->order('publishtime DESC')->field('title,description AS content,id AS url,litpic AS picurl,cid')->select();
        print_r($table_name);
        die;

        /*
            Array
        (
            [title] => 神秘的海底生物美丽水母图片手机壁纸
            [content] => 撒旦法斯蒂芬森答复实打实的发生大幅阿斯蒂芬是大幅度范德萨阿斯蒂芬第三方大师法的撒发的撒发
            [url] => 82
            [picurl] => /Uploads/image/2015-04-02/551ca29b9ce91.png
        )
Mobile/Show/index/cid/5/id/30.html
         */
        $dbdata=M('article')->limit(8)->order('publishtime DESC')->field('title,description AS content,id AS url,litpic AS picurl,cid')->select();
        $dd=array();
        foreach ($dbdata as $key => $v) {
            $v['url']=C('cfg_weburl').'/Mobile/Show/index/cid/'.$v['cid'].'/id/'.$v['url'];
            unset($v['cid']);
            $dd[]=$v;
        }
        //$url=getContentUrl($v['id'],$v['cid'],$v['ename'],false,$v['jumpurl']);
        //$url=C('cfg_weburl').str_replace("/".C('cfg_hou_tai'),'',$url);
        header("Content-Type:text/html; charset=utf-8");
        print_r('<pre>');
        print_r($dd);
        print_r('</pre>');
        print_r('<pre>');
        print_r($dbdata);
        print_r('</pre>');
    }

   
}
